package com.somiz.article;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.List;

import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.border.LineBorder;

import org.hibernate.Session;

import com.gest.util.FilterComboBox;
import com.gest.util.PdfUtil;
import com.itextpdf.text.Document;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfWriter;
import com.somiz.famille.Famille;
import com.somiz.gamme.Gamme;
import com.somiz.main.Control;
import com.somiz.main.Principal;
import com.somiz.structure.Structure;
import com.tech.hibernate.HibernateUtil;

/**
 * 
 * @author kacem
 * @version 1.0
 * 
 */
public class ArticlePanListe extends JPanel {
	private static final long serialVersionUID = 2672634149992839657L;
	private ModelListeArticle modelListeArticle = new ModelListeArticle();
	private List<Article> articles = new ArrayList<Article>();;
	private JTable tableau;
	private JTextField T_code;
	private FilterComboBox C_famille;
	private FilterComboBox C_gamme;
	private FilterComboBox C_strct;

	public ArticlePanListe() {
		Session session = HibernateUtil.getSessionFactory().openSession();
		C_famille = ListeCombFamille(session, C_famille);
		C_famille.getTextfield().addKeyListener(new KeyAdapter() {
			@Override
			public void keyReleased(KeyEvent arg0) {
				Session session = HibernateUtil.getSessionFactory()
						.openSession();
				actualisationFiltre(session);
				session.close();
			}
		});
		C_famille.addItemListener(new ItemListener() {
			public void itemStateChanged(ItemEvent e) {
				Session session = HibernateUtil.getSessionFactory()
						.openSession();
				actualisationFiltre(session);
				session.close();
			}
		});
		C_gamme = ListeCombGamme(session, C_gamme);
		C_gamme.getTextfield().addKeyListener(new KeyAdapter() {
			@Override
			public void keyReleased(KeyEvent arg0) {
				Session session = HibernateUtil.getSessionFactory()
						.openSession();
				actualisationFiltre(session);
				session.close();
			}
		});
		C_gamme.addItemListener(new ItemListener() {
			public void itemStateChanged(ItemEvent e) {
				Session session = HibernateUtil.getSessionFactory()
						.openSession();
				actualisationFiltre(session);
				session.close();
			}
		});
		C_strct = ListeCombStructure(session, C_strct);
		C_strct.getTextfield().addKeyListener(new KeyAdapter() {
			@Override
			public void keyReleased(KeyEvent arg0) {
				Session session = HibernateUtil.getSessionFactory()
						.openSession();
				actualisationFiltre(session);
				session.close();
			}
		});
		C_strct.addItemListener(new ItemListener() {
			public void itemStateChanged(ItemEvent e) {
				Session session = HibernateUtil.getSessionFactory()
						.openSession();
				actualisationFiltre(session);
				session.close();
			}
		});
		session.close();
		setLayout(null);
		tableau = new JTable(modelListeArticle);
		tableau.setRowHeight(25);
		JScrollPane scrollPane = new JScrollPane(tableau);
		scrollPane.setBounds(0, 72, 913, 446);
		this.add(scrollPane);

		JPanel panel = new JPanel();
		panel.setLayout(null);
		panel.setBorder(new LineBorder(new Color(0, 0, 0)));
		panel.setBounds(186, 11, 629, 50);
		add(panel);

		JLabel lblCode = new JLabel("Code :");
		lblCode.setBounds(10, 4, 49, 34);
		panel.add(lblCode);

		T_code = new JTextField();
		T_code.setText("");
		T_code.setBounds(52, 4, 93, 34);
		panel.add(T_code);
		T_code.setColumns(10);

		C_famille.setBounds(196, 4, 93, 34);
		panel.add(C_famille);

		JLabel lblFamille = new JLabel("famille :");
		lblFamille.setBounds(155, 4, 49, 34);
		panel.add(lblFamille);

		C_gamme.setBounds(339, 4, 126, 34);
		panel.add(C_gamme);

		JLabel lblGamme = new JLabel("Gamme :");
		lblGamme.setBounds(299, 4, 49, 34);
		panel.add(lblGamme);

		C_strct.setBounds(527, 4, 93, 34);
		panel.add(C_strct);

		JLabel lblStructure = new JLabel("structure :");
		lblStructure.setBounds(475, 4, 53, 34);
		panel.add(lblStructure);

		JButton button = new JButton("");
		button.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				Session session = HibernateUtil.getSessionFactory()
						.openSession();
				Control.getArticleForm().vider(session);
				Control.getPrincipal()
						.getTabbedPane()
						.addTab("Equipements",
								new ImageIcon(
										Principal.class
												.getResource("/cc/black/png/cert_icon&16.png")),
								Control.getArticleForm(), null);
				Control.getPrincipal()
						.getTabbedPane()
						.setSelectedIndex(
								Control.getPrincipal().getTabbedPane()
										.getTabCount() - 1);
				session.close();
			}
		});
		button.setIcon(new ImageIcon(ArticlePanListe.class
				.getResource("/images/png/Add32.png")));
		button.setPreferredSize(new Dimension(50, 50));
		button.setMnemonic(KeyEvent.VK_ENTER);
		button.setBackground(Color.WHITE);
		button.setBounds(6, 11, 50, 50);
		add(button);

		JButton button_1 = new JButton("");
		button_1.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				Session session = HibernateUtil.getSessionFactory()
						.openSession();
				actualisationFiltre(session);
				session.close();
			}
		});
		button_1.setIcon(new ImageIcon(ArticlePanListe.class
				.getResource("/cc/black/png/reload_icon&32.png")));
		button_1.setPreferredSize(new Dimension(50, 50));
		button_1.setMnemonic(KeyEvent.VK_ENTER);
		button_1.setBackground(Color.WHITE);
		button_1.setBounds(66, 11, 50, 50);
		add(button_1);

		JButton button_2 = new JButton("");
		button_2.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				Session session = HibernateUtil.getSessionFactory()
						.openSession();
				creerPdfArticle(session, "c:/temp/listeArticle.pdf");
				PdfUtil.OuvrirePdf("c:/temp/listeArticle.pdf",
						"Parc informatique");
				session.close();
			}
		});
		button_2.setIcon(new ImageIcon(ArticlePanListe.class
				.getResource("/cc/black/png/doc_lines_stright_icon&32.png")));
		button_2.setPreferredSize(new Dimension(50, 50));
		button_2.setMnemonic(KeyEvent.VK_ENTER);
		button_2.setBackground(Color.WHITE);
		button_2.setBounds(128, 11, 50, 50);
		add(button_2);

		JButton button_3 = new JButton("");
		button_3.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				Session session = HibernateUtil.getSessionFactory()
						.openSession();
				viderFiltres(session);
				session.close();
			}
		});
		button_3.setIcon(new ImageIcon(ArticlePanListe.class
				.getResource("/cc/black/png/trash_icon&32.png")));
		button_3.setPreferredSize(new Dimension(50, 50));
		button_3.setMnemonic(KeyEvent.VK_ENTER);
		button_3.setBackground(Color.WHITE);
		button_3.setBounds(825, 11, 50, 50);
		add(button_3);

		tableau.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseClicked(MouseEvent arg0) {
				int selectedRow = tableau.rowAtPoint(arg0.getPoint());
				int selectedCol = tableau.columnAtPoint(arg0.getPoint());
				if (selectedRow != -1)
					tableau.changeSelection(selectedRow, -1, false, false);
				if (selectedCol != -1)
					tableau.changeSelection(-1, selectedCol, false, false);
				if (arg0.getClickCount() == 2) {
					JTable target = (JTable) arg0.getSource();
					int row = target.getSelectedRow();
					int column = target.getSelectedColumn();
					Session session = HibernateUtil.getSessionFactory()
							.openSession();
					Article article = new Article();
					article.setCode(tableau.getValueAt(row, 0).toString());
					article = Control.getArticleDao().TrouverAvecCode(article,
							session);
					Control.getArticleForm().vider(session);
					Control.getArticleForm().ArticleVersForm(article);
					Control.getArticleForm().setArticleId(article.getId());
					Control.getPrincipal()
							.getTabbedPane()
							.addTab("Article",
									new ImageIcon(
											Principal.class
													.getResource("/cc/black/png/cert_icon&16.png")),
									Control.getArticleForm(), null);
					Control.getPrincipal()
							.getTabbedPane()
							.setSelectedIndex(
									Control.getPrincipal().getTabbedPane()
											.getTabCount() - 1);
					session.close();
				}
			}
		});
		session = HibernateUtil.getSessionFactory().openSession();
		actualisationFiltre(session);
		session.close();
	}

	public void creerPdfArticle(Session session, String lien) {
		String FILE = lien;
		Font catFont = new Font(Font.SERIF, 18, Font.BOLD);
		PdfPTable table = new PdfPTable(7);
		try {
			Document document = new Document();
			PdfWriter.getInstance(document, new FileOutputStream(FILE));
			document.open();
			document.addTitle("Liste des equipement");
			Paragraph preface = new Paragraph();
			PdfUtil.addEmptyLine(preface, 2);
			document.add(preface);
			List<Article> articles = new ArrayList<Article>(0);
			articles = Control.getArticleDao().charger(new Article(), session);
			articles = filreCode(articles, T_code);
			articles = filreFamille(articles, C_famille);
			articles = filreGamme(articles, C_gamme);
			articles = filreStructure(articles, C_strct);
			table = modelListeArticle.CreerHeaderPdf(table);
			for (int i = 0; i < articles.size(); i++) {
				table = modelListeArticle.addObjectPDF(articles.get(i), table);
			}
			document.add(table);
			document.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void viderFiltres(Session session) {
		T_code.setText("");
		C_famille.RemplireComboListe(Control.getFamilleDao().ListeNomsFamille(
				session));
		C_gamme.RemplireComboListe(Control.getGammeDao()
				.ListeNomsGamme(session));
		C_strct.RemplireComboListe(Control.getStructureDao()
				.ListeCodesStructures(session));
	}

	public void actualisationFiltre(Session session) {
		modelListeArticle.removeAllObjects();
		List<Article> articles = new ArrayList<Article>(0);
		Article article = new Article();
		articles = Control.getArticleDao().charger(article, session);
		articles = filreCode(articles, T_code);
		articles = filreFamille(articles, C_famille);
		articles = filreGamme(articles, C_gamme);
		articles = filreStructure(articles, C_strct);
		for (int i = 0; i < articles.size(); i++) {
			modelListeArticle.addObject(articles.get(i));
		}
	}

	public FilterComboBox ListeCombStructure(Session session,
			FilterComboBox comboBox) {
		Structure structure = new Structure();
		List<Structure> structures = Control.getStructureDao().charger(
				structure, session);
		List<String> listeRet = new ArrayList<String>();
		listeRet.add("");
		if (structure != null) {
			for (int i = 0; i < structures.size(); i++) {
				listeRet.add(structures.get(i).getCode());
			}
		}
		comboBox = new FilterComboBox(listeRet);
		return comboBox;
	}

	public FilterComboBox ListeCombFamille(Session session,
			FilterComboBox comboBox) {
		Famille famille = new Famille();
		List<Famille> familles = Control.getFamilleDao().charger(famille,
				session);
		List<String> listeRet = new ArrayList<String>();
		listeRet.add("");
		if (famille != null) {
			for (int i = 0; i < familles.size(); i++) {
				listeRet.add(familles.get(i).getNom());
			}
		}
		comboBox = new FilterComboBox(listeRet);
		return comboBox;
	}

	public FilterComboBox ListeCombGamme(Session session,
			FilterComboBox comboBox) {
		Gamme gamme = new Gamme();
		List<Gamme> gammes = Control.getGammeDao().charger(gamme, session);
		List<String> listeRet = new ArrayList<String>();
		listeRet.add("");
		if (gamme != null) {
			for (int i = 0; i < gammes.size(); i++) {
				listeRet.add(gammes.get(i).getNom());
			}
		}
		comboBox = new FilterComboBox(listeRet);
		return comboBox;
	}

	public List<Article> filreCode(List<Article> articles, JTextField combo) {
		String sFiltre = combo.getText().toString();
		List<Article> articlesRet = new ArrayList<Article>();
		if (!combo.getText().toString().equals("")) {
			for (int i = 0; i < articles.size(); i++) {
				if (articles.get(i).getCode().length() >= combo.getText()
						.toString().length()
						&& sFiltre.equals(articles
								.get(i)
								.getCode()
								.substring(0,
										combo.getText().toString().length()))) {
					articlesRet.add(articles.get(i));
				}
			}
			return articlesRet;
		} else {
			return articles;
		}
	}

	public List<Article> filreFamille(List<Article> articles,
			FilterComboBox combo) {
		String sFiltre = combo.getSelectedItem().toString();
		List<Article> articlesRet = new ArrayList<Article>();
		if (!combo.getSelectedItem().toString().equals("")) {
			for (int i = 0; i < articles.size(); i++) {
				if (articles.get(i).getFamille() != null) {
					if (articles.get(i).getFamille().getNom().length() >= combo
							.getSelectedItem().toString().length()
							&& sFiltre.equals(articles
									.get(i)
									.getFamille()
									.getNom()
									.substring(
											0,
											combo.getSelectedItem().toString()
													.length()))) {
						articlesRet.add(articles.get(i));
					}
				}
			}
			return articlesRet;
		} else {
			return articles;
		}
	}

	public List<Article> filreGamme(List<Article> articles, FilterComboBox combo) {
		String sFiltre = combo.getSelectedItem().toString();
		List<Article> articlesRet = new ArrayList<Article>();
		if (!combo.getSelectedItem().toString().equals("")) {
			for (int i = 0; i < articles.size(); i++) {
				if (articles.get(i).getGamme() != null) {
					if (articles.get(i).getGamme().getNom().length() >= combo
							.getSelectedItem().toString().length()
							&& sFiltre.equals(articles
									.get(i)
									.getGamme()
									.getNom()
									.substring(
											0,
											combo.getSelectedItem().toString()
													.length()))) {
						articlesRet.add(articles.get(i));
					}
				}
			}
			return articlesRet;
		} else {
			return articles;
		}
	}

	public List<Article> filreStructure(List<Article> articles,
			FilterComboBox combo) {
		String sFiltre = combo.getSelectedItem().toString();
		List<Article> articlesRet = new ArrayList<Article>();
		if (!combo.getSelectedItem().toString().equals("")) {
			for (int i = 0; i < articles.size(); i++) {
				if (articles.get(i).getUtilisateur() != null) {
					if (articles.get(i).getUtilisateur().getStructure()
							.getCode().length() >= combo.getSelectedItem()
							.toString().length()
							&& sFiltre.equals(articles
									.get(i)
									.getUtilisateur()
									.getStructure()
									.getCode()
									.substring(
											0,
											combo.getSelectedItem().toString()
													.length()))) {
						articlesRet.add(articles.get(i));
					}
				}
			}
			return articlesRet;
		} else {
			return articles;
		}
	}

}
